import dayjs from 'dayjs';
import _, { now } from 'lodash';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  AreaChart,
  Area,
  ResponsiveContainer,
  CartesianAxis,
} from 'recharts';
import API from '@/http';
import weekOfYear from 'dayjs/plugin/weekOfYear';

dayjs.extend(weekOfYear);
const EchartsView = ({ option, title }: { option: string; title: string }) => {
  const { t } = useTranslation();
  const xAxis_mon = [
    t('Jan'),
    t('Feb'),
    t('Mar'),
    t('Apr'),
    t('May'),
    t('Jun'),
    t('Jul'),
    t('Aug'),
    t('Sep'),
    t('Oct'),
    t('Nov'),
    t('Dec'),
  ];

  const xAxis_week = [
    t('Mon'),
    t('Tue'),
    t('Wed'),
    t('Thu'),
    t('Fri'),
    t('Sat'),
    t('Sun'),
  ];

  const xAxis_type = ['12months', '6months', '30days', '7days'];
  const [echartsData, setEchartsData] = useState([]);
  const [xAxisType, setXAxisType] = useState(xAxis_type[0]);
  const [currTime, setCurrTime] = useState(dayjs());
  const currYear = useMemo(() => currTime.year(), [currTime]);
  const [nextStr, setNextStr] = useState(`${currYear + 1}`);
  const [prevStr, setPrevStr] = useState(`${currYear - 1}`);
  const [xAxis, setXAxis] = useState(xAxis_mon);
  const [time, setTime] = useState('');
  const nowTime = useRef(dayjs());
  const [showNext, setShowNext] = useState(false);

  const frtType = useMemo(
    () => [
      xAxisType.match(/\d/g)?.join(''),
      xAxisType.match(/[a-zA-Z]/g)?.join(''),
    ],
    [xAxisType]
  );
  useEffect(() => {
    if (xAxisType == xAxis_type[0]) {
      setXAxis(xAxis_mon);
      setNextStr(`${currYear + 1}`);
      setPrevStr(`${currYear - 1}`);
    }
    if (xAxisType == xAxis_type[1]) {
      setXAxis(xAxis_mon);
      setPrevStr(`${t('nextYear')}`);
      setNextStr(`${t('prevYear')}`);
    }
    if (xAxisType == xAxis_type[2]) {
      setXAxis(new Array(30).fill(null).map((t, i) => `${i + 1}`));
      setNextStr(`${t('nextMon')}`);
      setPrevStr(`${t('prevMon')}`);
    }
    if (xAxisType == xAxis_type[3]) {
      setXAxis(xAxis_week);
      setNextStr(`${t('nextWeek')}`);
      setPrevStr(`${t('prevWeek')}`);
    }
  }, [xAxisType, t, currYear]);

  useEffect(() => {
    const _tp = frtType[0];
    if (_tp == '12') setTime(currTime.format('YYYY'));
    if (_tp == '6')
      setTime(
        currTime.month() > 5
          ? `${currTime.format('YYYY-07')}/${currTime.format('YYYY-12')}`
          : `${currTime.format('YYYY-01')}/${currTime.format('YYYY-07')}`
      ); //2024-01/2024-07
    if (_tp == '30') setTime(currTime.format('YYYY-MM')); //2024-09
    if (_tp == '7') setTime(`${currTime.week() - 1}`);
    setShowNext(currTime.isBefore(nowTime.current));
  }, [currTime, frtType]);

  useEffect(() => {
    time && option && feach(time, option);
  }, [time, option]);

  const feach = (time: any, option: any) => {
    API.Home.stat({
      data: { type: xAxisType, option, time },
    }).then((res: any) => {
      setEchartsData(res?.list);
    });
  };

  const CustomTooltip = (e: any) => {
    const { active, payload, label } = e;
    if (active && payload && payload.length) {
      return (
        <div className='custom-border-outer rounded-sm'>
          <div className="custom-tooltip rounded-sm text-ff bg-black px-4 py-2">
            <p className="label text-12">{`${label} ${xAxisType.includes('months') ? currYear : `${currYear}/${currTime.month() + 1}`}`}</p>
            <p className="rounded-sm text-14 font-[600]">{`$: ${Math.floor(payload[0].value)}`}</p>
          </div>
        </div>
      );
    }
    return null;
  };

  const customTickFormatter = (value: any) => {
    if (value < 1000) return value;
    return `${Math.floor(value / 1000)}k`;
  };

  const nextFunc = () => {
    //@ts-ignore
    setCurrTime(currTime.add(parseInt(frtType[0] || '0'), frtType[1]));
  };

  const prevFunc = () => {
    //@ts-ignore
    setCurrTime(currTime.add(-parseInt(frtType[0] || '0'), frtType[1]));
  };

  return (
    <div className="w-full pb-4">
      <div className="text-16 text-ff pb-2 md:hidden">{title}</div>
      <div className="w-full rounded-sm bg-black p-5">
        <div className="flex w-full justify-between pb-6 pt-4 text-12 leading-140 md:text-14">
          <div className="text-16 text-ff"><div className='hidden md:block'>{title}</div></div>
          <ul className="flex cursor-pointer space-x-2 md:space-x-10">
            {xAxis_type.map((_t) => (
              <li
                key={_t}
                onClick={() => {
                  setCurrTime(dayjs());
                  setXAxisType(_t);
                }}
                className={`relative ${_t == xAxisType ? 'chart-type-underline text-red' : 'text-7b'}`}
              >
                {`${_t.replace('months', '').replace('days', '')} ${_t.includes('months') ? t('mon') : t('day')}`}
              </li>
            ))}
          </ul>
        </div>
        <ResponsiveContainer width="100%" height={300}>
          <AreaChart
            margin={{ top: 5, right: 0, left: 10, bottom: 5 }}
            data={echartsData.map((t, i) => {
              return Object.assign({ px: xAxis[i] }, t);
            })}
          >
            <CartesianGrid
              stroke="#34353f"
              strokeWidth={1}
              height={1}
              vertical={false}
            />
            <defs>
              <linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#f44b39" stopOpacity={0.3} />
                <stop offset="95%" stopColor="#e81da5" stopOpacity={0} />
              </linearGradient>
            </defs>
            <XAxis
              dataKey="px"
              tickMargin={10}
              axisLine={true}
              tick={{
                fontSize: 12,
              }}
              tickLine={{ stroke: '#343540', strokeWidth: 0 }}
            />
            <YAxis
              tick={{
                fontSize: 12,
              }}
              type="number"
              tickMargin={10}
              tickLine={{ stroke: '#ccc', strokeWidth: 0 }}
              axisLine={false}
              tickFormatter={customTickFormatter}
            />
            <Tooltip content={<CustomTooltip />} cursor={{stroke: '#ed2e80', strokeWidth: 1}} viewBox={{background: 'red',width: 100,height:100}}/>
            <Area
              type="monotone"
              dataKey="value"
              stroke="#e81da5"
              fill="url(#colorUv)"
              strokeWidth={3}
              fillOpacity={1}
            />
          </AreaChart>
        </ResponsiveContainer>
      </div>
      <div className="flex w-full mt-2 justify-between text-12 leading-140 md:text-14">
        <div onClick={prevFunc} className="flex cursor-pointer text-ff">
          <div>&lt;</div>
          <div className="pl-1 ml-2">{prevStr}</div>
        </div>
        {showNext && (
          <div onClick={nextFunc} className="flex cursor-pointer text-ff">
            <div className="pr-1 mr-2">{nextStr}</div>
            <div>&gt;</div>
          </div>
        )}
      </div>
    </div>
  );
};

export default EchartsView;
